package com.topsun.framework.common.redis;

import com.topsun.framework.common.core.constants.CoreConstants;
import com.topsun.framework.common.core.util.StringPool;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Objects;

public class KeyPrefixSerializer extends StringRedisSerializer {

    private static String prefix;

    public static void setPrefix(String prefix) {
        KeyPrefixSerializer.prefix = prefix;
        if (Objects.nonNull(prefix)) {
            KeyPrefixSerializer.prefix = prefix + StringPool.COLON;
        }
    }

    @Override
    public String deserialize(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        String key = new String(bytes, CoreConstants.CHARSET_UTF_8);
        if (null != prefix) {
            key = key.replaceAll(key, StringPool.EMPTY);
        }
        return key;
    }

    @Override
    public byte[] serialize(String string) {
        if (null == string) {
            return null;
        }
        if (null != prefix) {
            string = prefix + string;
        }
        return string.getBytes(CoreConstants.CHARSET_UTF_8);
    }
}
